package com.ycy;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.*;
import com.mongodb.util.JSONParseException;
import org.bson.BsonArray;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.LimitOperation;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class MongoCollectionDemo {

  static MongoCollection<Document> coll;
  static MongoClient mongoClient = null;

  @Before
  public void before() {

    try {
      //连接MongoDB服务器，端口号为27017
      //MongoClient mongoClient = new MongoClient("localhost", 27017);
      mongoClient =
              MongoClients.create("mongodb://@127.0.0.1:27017/?authSource=rdfa-bp-web-xinzhi&readPreference=primary&appname=MongoDB%20Compass&ssl=false");
      //连接数据库
      MongoDatabase mDatabase = mongoClient.getDatabase("rdfa-bp-web-xinzhi");  //test可选
      System.out.println("Connect to database successfully!");
      System.out.println("MongoDatabase info is : " + mDatabase.getName());
      coll = mDatabase.getCollection("procInst");

//      MongoCollectionDemo mongoCollectionDemo = new MongoCollectionDemo();
//      mongoCollectionDemo.aggDate();

    } catch (Exception e) {
      e.printStackTrace();
//      System.err.println(e.getClass().getName() + ": " + e.getMessage());
//      mongoClient.close();
    }
  }

  public void dofind() {
    BsonArray bsonValues = new BsonArray();
    FindIterable<Document> documents = coll.find();

  }

  public void agg() {
    BsonArray bsonValues = new BsonArray();
    bsonValues.add(
            new BsonDocument("$match",
                    new BsonDocument("appName", new BsonString("yunwei-app")))
    );
    List aggregate = aggregate(bsonValues);
    System.out.println(aggregate);
  }

  @Test
  public void aggDate() {
    try {
      String rawQuery = "  [\n" +
              "    {\n" +
              "      \"$match\": {\n" +
              "         \"$or\":[\n" +
              "           {\"startTime\": {$gte:{%startTime},$lt:{%endTime}}},\n" +
              "         ]\n" +
              "      }\n" +
              "    } ]";
      Calendar instance = Calendar.getInstance();
      instance.set(Calendar.YEAR, 2021);
      instance.set(Calendar.MONTH, 1);

      Date start = instance.getTime();
      Date end = new Date();
      String queryStr = rawQuery
              .replace("{%startTime}", String.valueOf("new Date(" + start.getTime()) + ")")
              .replace("{%endTime}", String.valueOf("new Date(" + end.getTime()) + ")");
      BsonArray bsonValues = BsonArray.parse(queryStr);
      List aggregate = aggregate(bsonValues);
      System.out.println(aggregate);

    } finally {
      mongoClient.close();
    }
    mongoClient.close();
  }

  @Test
  public void aggDate11() {
    try {


      String s = "[\n" +
              "  {\n" +
              "      \"$match\": {\"tenantId\": \"middleware\"}\n" +
              "  },\n" +
              "  {\n" +
              "      \"$unwind\": \"$tasks\"\n" +
              "  },\n" +
              "  {\n" +
              "      \"$match\": {\"tasks.taskStartTime\": {\"$gte\": {\"$date\": 1614668400000}, \"$lt\": {\"$date\": 1758668400000}}, \"tasks.taskType\": \"userTask\"}\n" +
              "  },\n" +
              "  {\n" +
              "      \"$group\": {_id: '$taskInstId', 'sum': { $sum: 1}}\n" +
              "  },\n" +
              "  {\n" +
              "      \"$group\": {_id: null, count: {'$sum': '$sum'}}\n" +
              "  },\n" +
              "  {\n" +
              "      \"$project\": {\"_id\": 0, \"count\": 1}\n" +
              "  }\n" +
              "]\n";

      BsonArray parse = BsonArray.parse(s);
      List aggregate = aggregate(parse);
      System.out.println(aggregate);
    } finally {
      mongoClient.close();
    }


  }


  public List aggregate(List pipe) {
    ArrayList list = new ArrayList();
    coll.aggregate(pipe, Document.class).into(list);
    return list;
  }

  @Test
  public void test4() {


    ServerAddress serverAddress = new ServerAddress("10.19.151.197", 27017);
    MongoCredential mongoCredential = MongoCredential.createCredential("bocom", "admin", "Bocom_123".toCharArray());
// 第一个"admin" 为账号，第二个"admin"为创建账户时的数据库名称，第三个参数为密码
    com.mongodb.MongoClient mongoClient = new com.mongodb.MongoClient(serverAddress, mongoCredential, MongoClientOptions.builder().build());

    MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "saas_qrcode");

    System.out.println("Connect to database successfully!");

    String openId = "oTjJv5erb4yIFyBN4lrgNe77txNg";
    Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(Criteria.where("openId").is(openId).
                    and("qrCodeId").is(85).
                    and("form.formId").is(68)
                    .and("form.delete").exists(true)),
            Aggregation.sort(Sort.Direction.DESC, "commitTime"),
            Aggregation.limit(1)
            );

    // 执行查询
    AggregationResults<MongoDataMap> groupResults =
            mongoTemplate.aggregate(aggregation, "form_data", MongoDataMap.class);
    List<MongoDataMap> mappedResults = groupResults.getMappedResults();
    System.out.println(JSONObject.toJSONString(mappedResults));

    for (MongoDataMap mappedResult : mappedResults) {
      System.out.println(mappedResult.get("_id"));
    }

    System.out.println(groupResults.getMappedResults().size());

    LimitOperation limit = aggregation.limit(1);
    AggregationResults<MongoDataMap> form_data = mongoTemplate.aggregate(aggregation, "form_data", MongoDataMap.class);
    for (MongoDataMap mappedResult : form_data) {
      System.out.println(mappedResult.get("_id"));
    }

  }

}
